package cn.liyunqi.ttv.web.controller;

import cn.liyunqi.core.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/clientWechat")
public class ClientWeChatController {
    /**
     * 微信扫码
     * @return
     */
    @RequestMapping(value = "/qrcode",method = RequestMethod.GET)
    public HttpServletResponse getMail(HttpServletRequest request,HttpServletResponse response){

        String redirect_uri="http://nyt5vv.natappfree.cc/clientWechat/success";
        redirect_uri=getURLEncoderString(redirect_uri);//urlencode(redirect_uri);//该回调需要url编码
        String appID="wxa24be133e4bba3ff";
        String scope="snsapi_login";//写死，微信暂时只支持这个值
//准备向微信发请求
        String url = "https://open.weixin.qq.com/connect/qrconnect?appid="  + appID + "&redirect_uri=" + redirect_uri
                +"&response_type=code&scope="+scope +"&state=STATE#wechat_redirect";
//请求返回的结果(实际上是个html的字符串)


        try {

            String result = sendGet(url,null);//(url);
//替换图片的src才能显示二维码
            result = result.replaceAll("/connect/qrcode/","https://open.weixin.qq.com/connect/qrcode/");////str_replace("/connect/qrcode/", "https://open.weixin.qq.com/connect/qrcode/", );

            response.setContentType("text/html");
            response.getOutputStream().write(result.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;
    }
    @RequestMapping(value = "/qrcode/web",method = RequestMethod.GET)
    public String qrcode(HttpServletRequest request,HttpServletResponse response){



        return "wechatlogin";
    }
    @RequestMapping(value = "/success", method = RequestMethod.GET)
    public String query(ModelMap model) {
        model.addAttribute("name", "123");
        model.addAttribute("query", "123");
        model.addAttribute("submit", "123");
        return "hello";
    }

    private final static String ENCODE = "UTF-8";
    /**
     * URL 解码
     *
     * @return String
     * @author lifq
     * @date 2015-3-17 下午04:09:51
     */
    public static String getURLDecoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLDecoder.decode(str, ENCODE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * URL 转码
     *
     * @return String
     * @author lifq
     * @date 2015-3-17 下午04:10:28
     */
    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, ENCODE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String sendGet(String url, Map<String,String> paramMap) throws IOException {
        String result = "";
        BufferedReader in = null;
        String param = "";
        try {

            if(paramMap != null){

                for (String key : paramMap.keySet()) {
                    //map.keySet()返回的是所有key的值
                    String str = paramMap.get(key);//得到每个key多对用value的值
                    param = param + "&" + key + "=" + getURLEncoderString(str);
                }
                if(!StringUtil.isEmptyOrNull(param)){
                    param = "?" + param.substring(1);
                }
            }

            String urlNameString = url  + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");


            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"gbk"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            throw e;
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
}
